<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>用户表格</title>
  <link rel="stylesheet" href="static/common/layui/css/layui.css" media="all">
  <link rel="stylesheet" href="static/common/bootstrap/css/bootstrap.min.css" media="all">
  <script src="static/common/jquery-3.3.1.min.js"></script>
  <style>
    *{
        list-style: none;
        margin: 0px;
        padding: 0px;
    }
    html,body{
      position: relative;
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  </style>
</head>
<body>
<table id="user" lay-filter="userInfo"></table>
<script type="text/html" id="barDemo">
    <a class="layui-btn" lay-event="edit" style="line-height: 30px;">编辑</a>
    <a class="layui-btn layui-btn-danger" lay-event="del" style="line-height: 30px;">删除</a>
</script>
<script type="text/html" id="global_operate">
      <a id="addUser" class="layui-icon layui-icon-add-1" lay-event="add" style="font-size: 16px;cursor: pointer;color: #33333F;border:1px solid #CCCCCC;padding: 4px;margin:0 15px 0 33px;"></a> 
      <a id="patchDelete" class="layui-icon layui-icon-delete" data-type="getCheckData" lay-event="delete" style="font-size: 16px;cursor: pointer;color: #7D7C7D;border:1px solid #CCCCCC;padding: 4px;"></a> 
</script>
<script src="static/common/layui/layui.js"></script>
<script>
  /*序列化表格*/
  $.fn.serializeObject = function()
  {
      var o = {};
      var a = this.serializeArray();
      $.each(a, function() {
          if (o[this.name] !== undefined) {
              if (!o[this.name].push) {
                  o[this.name] = [o[this.name]];
              }
              o[this.name].push(this.value || '');
          } else {
              o[this.name] = this.value || '';
          }
      });
      return o;
  };
  layui.use('table', function(){
    var table = layui.table;
    
    //第一个实例
    table.render({
      elem: '#user'
      ,height: 480
      ,url: '/user_module/alluser' //数据接口
      ,page: true //开启分页
      ,toolbar: '#global_operate'//显示默认工具条
      ,limit:10
      ,totalRow: true
      ,cols: [[ //表头
        {checkbox: true}
        ,{field: 'uId', title: 'ID', width:'5%', sort: true}
        ,{field: 'uName', title: '用户名', width:'22%'}
        ,{field: 'uPhone', title: '手机', width:'22%'}
        ,{field: 'uEmail', title: '邮箱', width:'22%'} 
        ,{fixed: 'right', title:'操作',align:'center', toolbar: '#barDemo'} 
      ]]
      ,response: {
          statusName: 'status' //规定数据状态的字段名称，默认：code
          ,statusCode: 200 //规定成功的状态码，默认：0
          ,msgName: 'msg' //规定状态信息的字段名称，默认：msg
          ,dataName: 'products' //规定数据列表的字段名称，默认：data
          ,countName: 'total'
          ,limit:'limit'
      } 
    });
    //批量删除
    var $ = layui.$, active = {
      getCheckData: function(){ //获取选中数据
        var checkStatus = table.checkStatus('user')
        ,data = checkStatus.data;
        var ids = new Array();
        for(var i=0;i<data.length;i++){
            ids.push(data[i].uId);
        }
        var jsonstr=JSON.stringify({'ids':String(ids)});
        fetch('/user_module/users', {
            method: 'DELETE'
            ,body: jsonstr
        }).then(res => res.json()).catch(error => console.error(error))
        .then(function(response){
          if(response.status==401){
            layer.open({
                btn:['确定']
                ,content: response.msg
            })   
          }else if(response.status==200){
            layer.open({
              content: response.msg //这里content是一个普通的String
              ,success: function(layero, index){
                var btn = layero.find('.layui-layer-btn');
                btn.find('.layui-layer-btn0').on('click',function(){
                  window.location.reload();
                })
              }
            });
          }
        });
      }
    };
    $('#patchDelete').on('click', function(){
      var type = $(this).data('type');
      active[type] ? active[type].call(this) : '';
    });
    //监听行工具事件
    table.on('tool(userInfo)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
      var data = obj.data //获得当前行数据
      ,layEvent = obj.event; //获得 lay-event 对应的值
      if(layEvent === 'del'){
        layer.confirm(
          '真的删除用户~'+data.uName+'~么?'
          , {
              title:'用户删除'
          }
          ,function(index){
              obj.del(); //删除对应行（tr）的DOM结构
              layer.close(index);
              //向服务端发送删除指令
              fetch('/user_module/user/'+data.uId, {
                  method: 'DELETE'
              }).then(res => res.json()).catch(error => console.error(error))
              .then(function(response){
                  if(response.status==401){
                    console.log(response.msg);     
                  }else if(response.status==200){
                    console.log(response.msg);   
                    window.location.reload();
                  }
              });
        });
      } else if(layEvent === 'edit'){
          layer.open({
              title:'用户信息修改'
              ,content: `<form id="upadate_form" class="layui-form" action="" lay-filter="example" style="position:relative;top: 40px;left: -22px;">
                        <input type="hidden" name="uId" value=`+data.uId+` lay-verify="title" autocomplete="off" placeholder="请输入用户名" class="layui-input">
                        <div class="layui-form-item">
                          <label class="layui-form-label">用户名</label>
                          <div class="layui-input-block">
                            <input type="text" name="uName" value=`+data.uName+` lay-verify="title" autocomplete="off" placeholder="请输入用户名" class="layui-input">
                          </div>
                        </div>
                        <div class="layui-form-item">
                          <label class="layui-form-label">手机</label>
                          <div class="layui-input-block">
                            <input type="number" name="uPhone" value=`+data.uPhone+` placeholder="请输入手机号" autocomplete="off" class="layui-input">
                          </div>
                        </div>
                        <div class="layui-form-item">
                          <label class="layui-form-label">邮箱</label>
                          <div class="layui-input-block">
                            <input type="text" name="uEmail" value=`+data.uEmail+` placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                          </div>
                        </div>
                        </form>`,
              btn: ['修改', '取消'],
              area: ['500px', '350px'],
              success: function(layero, index){
                var btn = layero.find('.layui-layer-btn');
                btn.find('.layui-layer-btn0').on('click',function(){
                  var jsonStr = JSON.stringify($("#upadate_form").serializeObject());
                  fetch('/user_module/user', {
                      method: 'PUT'
                      ,body: jsonStr,//data是当前行的数据
                      headers: new Headers({
                        'Content-Type': 'application/json;charset=utf-8'
                      })
                  }).then(res => res.json()).catch(error => console.error(error))
                  .then(function(response){
                      if(response.status==402){ 
                        layer.open({
                          title: '错误信息'
                          ,content: response.msg
                        }); 
                      }else if(response.status==200){
                        window.location.reload();
                      }
                  });
                });
              }
          });  
      }
    });
      $(document).ready(function(){
          addUserInfo();//添加新的用户
      });
      function addUserInfo(){
          /*用户添加*/
          $('#addUser').on('click', function(){
            layer.open({
                title:'添加用户'
                ,btn:['添加','取消']
                ,area: ['500px', '400px']
                ,content: `<form id="insert_form" class="layui-form" action="" lay-filter="example" style="position:relative;top:10px;left: -35px;">
                          <div class="layui-form-item">
                            <label class="layui-form-label">用户名</label>
                            <div class="layui-input-block">
                              <input type="text" name="uName" lay-verify="title" autocomplete="off" placeholder="请输入用户名" class="layui-input">
                            </div>
                          </div>
                          <div class="layui-form-item">
                            <label class="layui-form-label">密码</label>
                            <div class="layui-input-block">
                              <input type="password" name="uPwd" lay-verify="title" autocomplete="off" placeholder="请输入密码" class="layui-input">
                            </div>
                          </div>
                          <div class="layui-form-item">
                            <label class="layui-form-label">手机</label>
                            <div class="layui-input-block">
                              <input type="number" name="uPhone" placeholder="请输入手机号" autocomplete="off" class="layui-input">
                            </div>
                          </div>
                          <div class="layui-form-item">
                            <label class="layui-form-label">邮箱</label>
                            <div class="layui-input-block">
                              <input type="text" name="uEmail" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
                            </div>
                          </div>
                          </form>`,
                          success: function(layero, index){
                              var btn = layero.find('.layui-layer-btn');
                              btn.find('.layui-layer-btn0').on('click',function(){
                                var jsonStr = JSON.stringify($("#insert_form").serializeObject());
                                fetch('/user_module/user', {
                                    method: 'PUT'
                                    ,body: jsonStr,//data是当前行的数据
                                    headers: new Headers({
                                      'Content-Type': 'application/json;charset=utf-8'
                                    })
                                }).then(res => res.json()).catch(error => console.error(error))
                                .then(function(response){
                                    if(response.status==402){ 
                                      layer.open({
                                        title: '错误信息'
                                        ,content: response.msg
                                      }); 
                                    }else if(response.status==200){
                                      window.location.reload();
                                    }
                                });
                              });
                          }
            })
          })
      }
   
  });
</script>
</body>
</html>